package com.zhang.flink.example;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: 使用底层api实现wordCount
 * @author: zhang
 * @date: 2022/2/11 19:28
 */
public class WordCountWithProcess {
    public static void main(String[] args) throws Exception {
        // todo 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 9999)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] fields = value.split(" ");
                        for (String field : fields) {
                            out.collect(Tuple2.of(field, 1));
                        }
                    }
                })
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
                    //声明状态变量，作为累加器使用
                    private ValueState<Integer> accumulator;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        accumulator = getRuntimeContext().getState(
                                new ValueStateDescriptor<Integer>(
                                        "acc",
                                        Types.INT
                                )
                        );
                    }

                    @Override
                    public void processElement(Tuple2<String, Integer> value, KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                        // 当第一条数据到来直接更新累加器并输出
                        if (accumulator.value()==null){
                            accumulator.update(value.f1);
                        }else {
                            accumulator.update(accumulator.value()+ value.f1);
                        }
                        out.collect(Tuple2.of(value.f0,accumulator.value()));
                    }
                })
                .print();

        env.execute();
    }
}
